<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item class="smart-query-form-item" label="一级分类">
        <a-select v-model:value="queryForm.typeId1"
                  :field-names="{label: 'typeName',value: 'id'}"
                  :options="type1Options"
                  @change="typeChange(1)"
                  allowClear placeholder="选择分类" style="width: 200px">
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="二级分类">
        <a-select v-model:value="queryForm.typeId2"
                  :field-names="{label: 'typeName',value: 'id'}"
                  :options="type2Options"
                  @change="typeChange(2)"
                  allowClear placeholder="选择分类" style="width: 200px">
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="三级分类">
        <a-select v-model:value="queryForm.typeId"
                  :field-names="{label: 'typeName',value: 'id'}"
                  :options="typeOptions"
                  @change="typeChange(3)"
                  allowClear placeholder="选择分类" style="width: 200px">
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="状态">
        <a-select v-model:value="queryForm.status" allowClear placeholder="选择标签" style="width: 160px">
          <a-select-option :value="''">全部</a-select-option>
          <a-select-option :value="0">上架</a-select-option>
          <a-select-option :value="1">下架</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="型号名称">
        <a-input v-model:value="queryForm.modelName" placeholder="请输入型号名称" style="width: 160px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="resetPageNumAjaxQuery">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card>
    <div style="text-align: right;margin-bottom: 8px">
      <a-button type="primary" @click="changeEditStatus">{{ editStatus ? '退出编辑' : '编辑' }}</a-button>
    </div>
    <a-table
        v-if="!editStatus"
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :pagination="false"
        bordered
        rowKey="id"
        size="small"
    >
      <template #bodyCell="{ column, record, text,index }">
        <template v-if="column.dataIndex === 'index'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          <span :style="{color: text===0?'#87d068':'#f50'}">
            {{ text === 0 ? '上架' : text === 1 ? '下架' : '未知' }}
          </span>
        </template>
      </template>
    </a-table>

    <a-table
        v-if="editStatus"
        :columns="editStatusColumns"
        :dataSource="editStatusTableData"
        :pagination="false"
        bordered
        rowKey="id"
        size="small"
    >
      <template #bodyCell="{ column, record, text,index }">
        <template v-if="column.dataIndex === 'index'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'sort'">
          <a-input-number v-model:value="record.sort" min="0"
                          style="width: 130px">
          </a-input-number>
        </template>
        <template v-if="column.dataIndex === 'status'">
          <a-switch :checked="text===0"
                    @click="changeStatus(record)"/>
          <span :style="{color: text===0?'#87d068':'#f50'}">
            {{ text === 0 ? '上架' : text === 1 ? '下架' : '未知' }}
          </span>
        </template>
        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button danger type="link" @click="confirmDelete(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div v-if="editStatus" class="showAddModelBtn">
        <span @click="showAddModel">
        <PlusOutlined/>添加型号
        </span>
    </div>

    <div v-if="editStatus" style="text-align: right;">
      <a-button  @click="changeEditStatus">取消</a-button>
      <a-button type="primary" @click="save" style="margin-left: 8px">保存</a-button>
    </div>

  </a-card>

  <add-model-modal ref="addModelModalRef" @addModel="addModel"></add-model-modal>

</template>

<script setup>

import {onMounted, reactive, ref} from "vue";
import {mobileCategoryApi} from "/@/views/business/marketing/mobile-category/mobile-category";
import {message, Modal} from "ant-design-vue";
import {smartSentry} from "/@/lib/smart-sentry";
import {mobileModelApi} from "/@/views/business/marketing/mobile-model/mobile-model-api";
import AddModelModal from "/@/views/business/marketing/mobile-model/add-model-modal.vue";
import _ from 'lodash';

const queryFormDefault = {
  modelName: undefined,
  typeId1: undefined,
  typeId2: undefined,
  typeId: undefined,
  status: '',
};
const columns = [
  {
    width: 40,
    align: 'center',
    title: '序号',
    dataIndex: 'index',
  },
  {
    width: 80,
    align: 'center',
    title: '型号名称',
    dataIndex: 'modelName',
    ellipsis: true,
  },
  {
    width: 80,
    align: 'center',
    title: '排序',
    dataIndex: 'sort',
  },
  {
    width: 80,
    align: 'center',
    title: '状态',
    dataIndex: 'status',
  }
];
const editStatusColumns = [...columns,
  {
    width: 80,
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    fixed: 'right'
  }]
const tableLoading = ref(false);
const editStatus = ref(false);
const tableData = ref([]);
const editStatusTableData = ref([]); // 编辑的表格
const remoteIds = ref([]); // 服务器已关联的id列表
const toDelete = ref([]); // 要删除的关联（服务器）

const type1Options = ref([]);
const type2Options = ref([]);
const typeOptions = ref([]);
const queryForm = reactive({...queryFormDefault});
const addModelModalRef = ref();

onMounted(async () => {
  let response = await mobileCategoryApi.queryByTier({tier: 1});
  if (response.data.length) {
    type1Options.value = response.data;
  } else {
    message.error(`没有可选的一级分类`)
  }
});

// 分类过滤变化
async function typeChange(tier) {
  editStatusTableData.value = [];
  tableData.value = [];
  remoteIds.value = [];
  toDelete.value = [];
  editStatus.value = false;

  if (tier === 1) {
    queryForm.typeId2 = undefined;
    queryForm.typeId = undefined;
    type2Options.value = [];
    typeOptions.value = [];
    if (!queryForm.typeId1) {
      return;
    }
    let response = await mobileCategoryApi.queryByTier({tier: 2, parentId: queryForm.typeId1});
    if (response.data.length) {
      type2Options.value = response.data;
    } else {
      message.error(`没有可选的二级分类`)
    }
  }
  if (tier === 2) {
    queryForm.typeId = undefined;
    typeOptions.value = [];
    if (!queryForm.typeId2) {
      return;
    }
    let response = await mobileCategoryApi.queryByTier({tier: 3, parentId: queryForm.typeId2});
    if (response.data.length) {
      typeOptions.value = response.data;
    } else {
      message.error(`没有可选的三级分类`)
    }
  }

}
function resetPageNumAjaxQuery(){
  queryForm.pageNum = 1;
  ajaxQuery();
}

// 查询所有已关联型号
async function ajaxQuery() {
  if (!queryForm.typeId) {
    return message.error('请先选择三级分类');
  }
  try {
    let response = await mobileModelApi.queryByTypeId({
      modelName: queryForm.modelName,
      typeId: queryForm.typeId,
      status: queryForm.status,
    });
    tableData.value = response.data;
    editStatus.value = false;
    editStatusTableData.value = [];
    toDelete.value = [];

    let responseIds = await mobileModelApi.queryModelIds(queryForm.typeId);
    remoteIds.value = responseIds.data ? responseIds.data.split(',').map(i => i * 1) : [];
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// 重置查询条件
async function resetQuery() {
  Object.assign(queryForm, queryFormDefault);
  type2Options.value = [];
  typeOptions.value = [];
  remoteIds.value = [];
  toDelete.value = [];
  tableData.value = [];
  editStatusTableData.value = [];
}

function showAddModel() {
  console.log(editStatusTableData.value)
  addModelModalRef.value.showModal({
    disabledIds: [...remoteIds.value,...editStatusTableData.value.map(i=>i.modelId)]
  });
}

function addModel(v) {
  console.log(v);
  editStatusTableData.value.push(...v);
}

function changeEditStatus() {
  if (editStatus.value) {
    Modal.confirm({
      title: '提示',
      content: '确定要退出编辑吗?未保存的数据将会丢失',
      okText: '退出',
      okType: 'danger',
      onOk() {
        editStatus.value = !editStatus.value;
      },
      cancelText: '取消',
      onCancel() {
        return Promise.resolve();
      },
    });
  } else {
    editStatusTableData.value = _.cloneDeep(tableData.value);
    editStatus.value = !editStatus.value;
  }
}

// 删除
function confirmDelete(record) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除【' + record.modelName + '】吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      if (remoteIds.value.findIndex(i => i === record.modelId) !== -1) {
        toDelete.value.push({
          deleteFlag: 1,
          id: record.id,
          modelId: record.modelId,
          sort: record.sort,
          status: record.status,
        })
      }
      editStatusTableData.value = editStatusTableData.value.filter(i => i.modelId !== record.modelId);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

function changeStatus(record) {
  record.status = record.status === 0 ? 1 : 0;
}

async function save() {
  if (!queryForm.typeId) {
    return message.error('请先选择三级分类');
  }
  try {
    const typeToModels = editStatusTableData.value.map(item => ({
      deleteFlag: item.deleteFlag,
      id: item.id,
      modelId: item.modelId,
      sort: item.sort,
      status: item.status,
    }))
    console.log(toDelete.value)
    let response = await mobileModelApi.add({
      typeId: queryForm.typeId,
      typeToModels: [...typeToModels, ...toDelete.value],
    });
    toDelete.value = [];
    ajaxQuery();
  } catch (e) {
    smartSentry.captureError(e);
  }

}

</script>

<style scoped lang="less">

.showAddModelBtn {
  text-align: center;
  font-size: 16px;
  color: #00a0e9;
  font-weight: bold;

  span {
    cursor: pointer;
  }
}
</style>